package com.ruoyi.web.controller.market.special;

import cn.hutool.core.util.PhoneUtil;
import com.ruoyi.common.constant.UserConstants;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.utils.ShiroUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.db.domain.SpecialCostomInfo;
import com.ruoyi.db.domain.SpecialCostomUserInfo;
import com.ruoyi.db.domain.SysConstantInfo;
import com.ruoyi.framework.shiro.service.SysPasswordService;
import com.ruoyi.market.constant.SysConstantType;
import com.ruoyi.market.service.ISysConstantInfoService;
import com.ruoyi.special.service.ISpecialCostomInfoService;
import com.ruoyi.special.service.ISpecialCostomUserInfoService;
import com.ruoyi.special.service.ISpecialDataInfoService;
import com.ruoyi.special.service.ISpecialMemberService;
import com.ruoyi.system.service.ISysUserService;
import com.ruoyi.web.service.IMemberInfoHandleService;
import com.ruoyi.web.wapper.SpecialCostomUserInfoWapper;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

/**
 * 渠道信息Controller
 * 
 * @author ruoyi
 * @date 2022-08-04
 */
@Controller
@RequestMapping("/special/agency/user")
public class SpecialAgencyUserController extends BaseController
{
    private String prefix = "special/agency/user";

    @Autowired
    ISpecialMemberService specialMemberService;
    @Autowired
    ISpecialCostomInfoService specialCostomInfoService;
    @Autowired
    IMemberInfoHandleService memberInfoHandleService;
    @Autowired
    ISpecialDataInfoService specialDataInfoService;
    @Autowired
    ISpecialCostomUserInfoService specialCostomUserInfoService;
    @Autowired
    private ISysUserService sysUserService;
    @Autowired
    private SysPasswordService passwordService;
    @Autowired
    private ISysConstantInfoService sysConstantInfoService;

    @RequiresPermissions("special:agency:user")
    @GetMapping("")
    public String dataList()
    {
        return prefix + "/list";
    }

    @RequiresPermissions("special:agency:user")
    @PostMapping("/dataListInfo")
    @ResponseBody
    public TableDataInfo dataListInfo(SpecialCostomUserInfo specialCostomUserInfo)
    {

        SysUser sysUser = getSysUser();
        if (!sysUser.isAdmin()){
            // 设置，查询
            specialCostomUserInfo.setDeptId(sysUser.getDeptId());
        }

        startPage();
        List<Map<String, Object>> mapList = specialCostomUserInfoService.selectSpecialCostomUserInfoListMap(specialCostomUserInfo);
        mapList = new SpecialCostomUserInfoWapper(mapList).wrap();
        return getDataTable(mapList);
    }

    @RequiresPermissions("special:agency:user")
    @GetMapping("/add")
    public String add()
    {
        return prefix + "/add";
    }

    @RequiresPermissions("special:agency:user")
    @PostMapping("/add")
    @ResponseBody
    public AjaxResult addSave(SpecialCostomUserInfo specialCostomUserInfo)
    {
        SysUser curSysUser = getSysUser();
        // 查询当前登陆用户的信息
        SpecialCostomInfo costomInfo =
                specialCostomInfoService.getAccountInfoByDeptId(curSysUser.getDeptId());

        // 生成新的登陆用户的信息
        String phone = specialCostomUserInfo.getAdminUserPhone();
        SysUser sysUser = new SysUser();
        sysUser.setUserName(specialCostomUserInfo.getAdminUserName());
        sysUser.setLoginName(phone);
        sysUser.setPhonenumber(phone);

        if (!PhoneUtil.isMobile(phone))
        {
            return error("请填写正确的手机号");
        }
        else if (UserConstants.USER_NAME_NOT_UNIQUE.equals(sysUserService.checkLoginNameUnique(sysUser.getLoginName())))
        {
            return error("新增用户'" + sysUser.getLoginName() + "'失败，登录账号已存在");
        }
        else if (StringUtils.isNotEmpty(sysUser.getPhonenumber())
                && UserConstants.USER_PHONE_NOT_UNIQUE.equals(sysUserService.checkPhoneUnique(sysUser)))
        {
            return error("新增用户'" + sysUser.getLoginName() + "'失败，手机号码已存在");
        }

        String password = phone.substring(5);
        sysUser.setPassword(password);
        sysUser.setUserType(UserConstants.REGISTER_USER_TYPE);
        sysUser.setSalt(ShiroUtils.randomSalt());
        sysUser.setPassword(passwordService.encryptPassword(sysUser.getLoginName(), sysUser.getPassword(), sysUser.getSalt()));
        sysUser.setCreateBy(getLoginName());

        sysUser.setDeptId(costomInfo.getDeptId());
        SysConstantInfo constantInfo = sysConstantInfoService.getEntryByType(SysConstantType.TYPE_SPECIAL_MENU_ROLE_ID);
        sysUser.setRoleIds(new Long[]{Long.valueOf(constantInfo.getValue())});
        int i = sysUserService.insertUser(sysUser);
        if (i<1){
            return toAjax(0);
        }

        // 新增用户菜单用户的信息
        specialCostomUserInfo.setCostomId(costomInfo.getId());
        specialCostomUserInfo.setDeptId(costomInfo.getDeptId());
        specialCostomUserInfo.setAdminUserId(sysUser.getUserId());

        int i1 = specialCostomUserInfoService.insertSpecialCostomUserInfo(specialCostomUserInfo);
        if (i1 < 1){
            sysUserService.deleteUserById(sysUser.getUserId());
        }

        return toAjax(i1);
    }

    @RequiresPermissions("special:agency:user")
    @GetMapping("/edit/{id}")
    public String edit(@PathVariable("id") Long id, ModelMap mmap)
    {
        SpecialCostomUserInfo specialCostomUserInfo = specialCostomUserInfoService.selectSpecialCostomUserInfoById(id);
        mmap.put("specialCostomUserInfo", specialCostomUserInfo);
        return prefix + "/edit";
    }

    @RequiresPermissions("special:agency:user")
    @PostMapping("/edit")
    @ResponseBody
    public AjaxResult editSave(SpecialCostomUserInfo specialCostomUserInfo)
    {
        return toAjax(specialCostomUserInfoService.updateSpecialCostomUserInfo(specialCostomUserInfo));
    }

    /**
     * 删除用户信息
     * @param ids
     * @return
     */
    @RequiresPermissions("special:agency:user")
    @PostMapping( "/remove")
    @ResponseBody
    public AjaxResult remove(String ids)
    {
        return toAjax(specialCostomUserInfoService.deleteSpecialCostomUserInfoByIds(ids));
    }

    @RequiresPermissions("special:agency:user")
    @PostMapping("/changeStatus")
    @ResponseBody
    public AjaxResult changeStatus(SpecialCostomUserInfo specialCostomUserInfo)
    {
        return toAjax(specialCostomUserInfoService.updateSpecialCostomUserInfo(specialCostomUserInfo));
    }

}
